var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');



var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var gradeRouter = require('./routes/grade');
var goodsRouter = require('./routes/goods');
var carRouter = require('./routes/car');

var app = express();

// view engine setup  (模版引擎 -> 去除)
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 允许访问api的时候cors跨域
// app.use((req, res, next) => {

//   console.log(req.headers.origin);
//   // 增加了cors跨域的请求头
//   res.header("Access-Control-Allow-Origin", "*");  // 允许所有人访问
//   // res.header("Access-Control-Allow-Origin", "http://127.0.0.1:5050");  // 只允许http://127.0.0.1:5050访问
//   // res.header("Access-Control-Allow-Origin", "http://192.168.53.195:5050");  // 只允许http://127.0.0.1:5050访问
//   res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
//   res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//   next();
// })

// var whiteList = ["http://127.0.0.1:8086", "http://127.0.0.1:5050"]; // 允许访问的域名

// app.use((req, res, next) => {
//   if (whiteList.includes(req.headers.origin)) {
//     // 增加了cors跨域的请求头
//     res.header("Access-Control-Allow-Origin", "*");  // 允许所有人访问
//     res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
//     res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//     next();
//   } else {
//     res.send("充钱吧!");
//   }
// })







app.use('/', indexRouter);
app.use('/user', userRouter);
app.use('/grade', gradeRouter);
app.use('/goods', goodsRouter);
app.use('/car', carRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
